<template>
    <BaseDialog title="导入" :handleCancel="handleCancel" :dialogVisible="props.dialogVisible" width="1100px">
        <div class="list">
            <div v-for="item in stepList" :key="item.value" :class="step >= item.value ? 'item item-select' : 'item'">
                <div class="spare">{{ item.value }}</div>
                <div>{{ item.name }}</div>
            </div>
        </div>
        <template v-if="step == 1">
            <div class="upload-content">
                <div class="item">
                    <div class="icon"><el-icon style="margin-top:5px;transform: rotate(180deg);" color="#909399"
                            size="30px">
                            <UploadFilled />
                        </el-icon></div>
                    <div style="padding: 10px;">
                        <div style="font-weight:bold">填写导入数据信息</div>
                        <div style="margin-top:5px;color: #999999;">请按照数据模板的格式准备导入数据，模板中的表头名称<span
                                style="color:#F56C6C">不可更改</span>，表头行不能<span style="color:#F56C6C">删除</span></div>
                        <!--  :href="`${url}${props.downUrl}`"  :href="`${baseUrl}/robot-api${props.downUrl}`"-->

                        <el-link :href="`${baseUrl}/robot-api${props.downUrl}`" style="margin-top:5px;" :underline="false"
                            link type="primary" size="small" :download="`${props.fileName}.xlsx`">下载模板</el-link>
                    </div>

                </div>
                <div class="item">
                    <div class="icon"><el-icon style="margin-top:5px" color="#909399" size="30px">
                            <UploadFilled />
                        </el-icon></div>
                    <div style="padding: 10px;">
                        <div style="font-weight:bold">上传填好的信息表</div>
                        <div style="margin-top:5px;color: #999999;">文件后缀名必须为<span style="color:#F56C6C">xls</span> 或<span
                                style="color:#F56C6C">xlsx</span> (即Excel格式)，文件大小不得大于<span
                                style="color:#F56C6C">10</span>M，最多支持导入<span style="color:#F56C6C">2000</span>条数据</div>
                        <el-upload ref="uploadRef" v-model:file-list="fileList" class="upload-demo" accept=".xls,.xlsx"
                            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" :auto-upload="false"
                            :on-change="handleChange">
                            <el-link v-if="fileList.length == 0" style="margin-top:5px;" :underline="false" link
                                type="primary" size="small">上传文件</el-link>

                        </el-upload>

                    </div>
                </div>
                <div class="worring">
                    <div><el-icon style="margin-top:5px" color="#fe9400" size="30px">
                            <WarningFilled />
                        </el-icon></div>
                    <div style="margin-left:10px">
                        <div>特别提示</div>
                        <div style="margin-top:5px;color: #999999;font-size: 12px;">导入过程中如发现已有数据或数据有误，则不会导入数据。</div>
                    </div>
                </div>

            </div>
            <div class="form-btn">

                <el-button @click="handleCancel"> 取 消 </el-button>
                <el-button type="primary" @click="upLoadFile()">
                    下一步
                </el-button>

            </div>
        </template>
        <div style="height:500px" v-loading="loadingExport" v-if="step == 2" element-loading-text="上传中...">
        </div>
        <div v-if="step == 3">
            <div class="result">
                <div class="icon"><el-icon style="margin-top:5px" color="#909399" size="30px">
                        <el-icon>
                            <InfoFilled />
                        </el-icon>
                    </el-icon></div>
                <div style="padding: 16px 40px">
                    <div><span style="font-weight:bold">导入成功数据条数: </span><span style="color:#67C23A">{{ successNum
                    }}条</span>
                    </div>
                    <div style="margin-top:5px"><span style="font-weight:bold">导入失败数据条数: </span><span
                            style="color:#F56C6C">{{ failNum }}条</span></div>

                </div>

            </div>
            <div style="margin-top:20px;border:1px solid #DCDFE6;padding: 16px;" v-if="failNum > 0">
                <div style="font-weight:bold">导入失败数据预览：</div>
                <el-table id="my-table-id" v-if="props.type == 'grid'" style="margin-top:20px;width: 100%" border
                    v-loading="loading" element-loading-text="加载中..." :data="tableData" max-height="400px">
                    <el-table-column prop="powerCode" label="供电单位编号" />
                    <el-table-column prop="powerName" label="供电单位名称" />
                    <el-table-column prop="lineCode" label="线路编号" />
                    <el-table-column prop="lineName" label="线路名称" />
                    <el-table-column prop="areaCode" label="台区编号" />
                    <el-table-column prop="areaName" label="台区名称" />
                    <el-table-column prop="exceptionStr" label="失败原因" />

                </el-table>
                <el-table id="my-table-id" v-if="props.type == 'message'" style="margin-top:20px;width: 100%" border
                    v-loading="loading" element-loading-text="加载中..." :data="tableData" max-height="400px">
                    <el-table-column prop="title" label="标题" width="120" />
                    <el-table-column prop="startTime" label="停电开始时间" minWidth="120" />
                    <el-table-column prop="endTime" label="停电结束时间" />
                    <el-table-column prop="content" label="内容" />
                    <el-table-column prop="areaCodes" label="停电台区编号" />
                    <el-table-column prop="exceptionStr" label="失败原因" />

                </el-table>

            </div>
            <div class="form-btn">

                <el-button @click="downFileData" v-if="failNum > 0"> <el-icon>
                        <Bottom></Bottom>
                    </el-icon>导出失败数据 </el-button>
                <el-button type="primary" @click="handleOk()">
                    确定
                </el-button>

            </div>
        </div>
    </BaseDialog>
</template>
<script setup lang="ts">

import type { FormInstance } from 'element-plus'
import { contentManagementService } from '@/api/contentManagement'
import { commonService } from '@/api/common'
import { Debounce } from '@/hooks/throttle'
import { getAuditStatus, getSendStatus } from '@/hooks/getStateName'
import { download } from '@/hooks/downLoad'
import openMsgBox from '@/hooks/messageBox.js'
import type { UploadProps, UploadUserFile, UploadInstance } from 'element-plus'
import { Bell, ElementPlus } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

import { saveAs } from "file-saver";
const props = defineProps({
    dialogVisible: {
        type: Boolean,
    },
    item: {
        type: Object,
    },
    handleSearch: {
        type: Function,
    },
    type: {
        type: String,
    },
    downUrl: {
        type: String,
    },
    fileName: {
        type: String,
    },
    exportFn: {
        type: Function,
    },
    downFile: {
        type: Function,
    },
})
const emit = defineEmits(['update:dialogVisible'])
const step = ref(1);
const stepList = ref([
    {
        name: '上传文件', value: 1,
    },
    {
        name: '导入数据', value: 2,
    },
    {
        name: '导入结果', value: 3,
    }
])
const url = import.meta.env.VITE_QIANKUN_PATH
const baseUrl = import.meta.env.VITE_BASE_URL
const handleCancel = () => {
    emit('update:dialogVisible', false)
    props.handleSearch();
}
const handleOk = () => {
    emit('update:dialogVisible', false)
    props.handleSearch();
}

const uploadRef = ref<UploadInstance>()
const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {

    console.log('uploadFile', uploadFile)
}
const upLoadFile = () => {
    if (fileList.value.length == 0) {

        ElMessage({
            message: '请先上传文件',
            type: 'warning',
        })
        return
    }
    step.value = 2;
    loadingExport.value = true
    exportExcel();
}
const loadingExport = ref(false)
const failNum = ref(0);
const successNum = ref(0);
const tableData = ref([]);
const exportExcel = () => {
    const formData = new FormData();
    formData.append('file', fileList.value[0].raw)
    props.exportFn(formData).then((res) => {
        setTimeout(() => {
            step.value = 3;
            loadingExport.value = false
            failNum.value = res.data.failNum;
            successNum.value = res.data.successNum;
            if (props.type == 'message')
                tableData.value = res.data.messageImportFailDtoList;
            if (props.type == 'grid')
                tableData.value = res.data.failAreaDtoList;
        }, 1000)
    }).catch(() => {
        step.value = 1;
        loadingExport.value = false
    })

}
const fileList = ref([]);
const loading = ref(false);
const downFileData = () => {
  /*   var table_elt = document.getElementById("my-table-id");
    var worksheet = XLSX.utils.table_to_sheet(table_elt, { raw: true });
    var workbook = XLSX.utils.book_new();
    var rows=[{ hpx: 20 }];
    tableData.value.forEach((item)=>{
        rows.push({ hpx: 40 })
    })
    worksheet['!rows']=rows;

    worksheet['!cols'] = props.type == 'grid' ? [{ wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }] : [{ wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }, { wch: 30 }]
    XLSX.utils.book_append_sheet(workbook, worksheet, '失败数据')
    XLSX.writeFile(workbook, "失败数据.xlsx"); */
    props.downFile({ data: tableData.value }).then((res) => {
        var blob = new Blob([res])
        let url = window.URL.createObjectURL(blob)
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '失败数据.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })
}
</script>
<style lang="scss" scoped>
.form-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 700px;
    margin: 0px auto;

    .item {
        display: flex;
        align-items: center;
        color: #333333;
    }

    .spare {
        text-align: center;
        color: #ffff;
        font-weight: 700;
        font-style: normal;
        font-size: 20px;
        background-color: #cccc;
        width: 26px;
        height: 26px;
        margin-right: 10px;

    }

    .item-select {
        .spare {
            background-color: #00bb9a;
        }
    }
}

.upload-content {
    width: 700px;
    margin: 0px auto;

    .item {
        margin-top: 20px;
        border: 1px solid #DCDFE6;
        display: flex;

        .icon {
            background: #F0F2F5;
            padding: 20px;
        }
    }

    .worring {
        border-width: 1px;
        border-style: solid;
        border-color: rgb(255, 235, 204);
        border-radius: 5px;
        background-color: #fdf6ec;
        padding: 16px;
        display: flex;
        margin-top: 20px;
    }
}

.result {
    margin-top: 20px;
    border: 1px solid #DCDFE6;
    display: flex;

    .icon {
        background: #F0F2F5;
        padding: 20px;
    }
}

.files {
    display: flex;
    font-size: 12px;

    .name {
        flex: 1;
        width: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
</style>
  